<template>
  <el-dialog class="public-dialog" title="费用导入" :modelValue="modelValue" align-center width="560" @close="handleClose" :close-on-click-modal="false">
    <p class="text-[14px] text-[#0a1431] leading-[20px] mb-[8px]">第 <span class="font-[600]">1</span> 步：点击下载模版</p>
    <a class="bg-[#FAFAFA] flex items-center justify-center rounded-[4px] py-[12px] cursor-pointer" @click="handleDownload">
      <div class="text-[#3366F1] flex items-center gap-1">
        <div class="dk-iconfont icon-Download"></div>
        下载模板
      </div>
    </a>
    <p class="text-[14px] text-[#0a1431] leading-[20px] my-[16px]">第 <span class="font-[600]">2</span> 步：按照模版要求填写</p>
    <p class="text-[14px] text-[#0a1431] leading-[20px] mb-[8px]">第 <span class="font-[600]">3</span> 步：上传填写完成的文件</p>
    <el-upload
      ref="upload"
      v-model:file-list="fileList"
      accept=".xlsx"
      class="v-import"
      :data="extraData"
      drag
      :auto-upload="false"
      :limit="1"
      :action="ossParams.host || ''"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :on-progress="handleUploadProgress"
      :on-error="handleUploadError"
      :on-change="handleChange"
      :on-success="handleUploadSuccess"
    >
      <div class="text-[#3366F1] flex items-center">
        <div class="dk-iconfont icon-Plus"></div>
        上传文件
      </div>
    </el-upload>
    <div class="text-[14px] text-[#333] mb-[4px]">备注信息</div>
    <el-input v-model="remark" type="textarea" placeholder="请输入备注信息" />
    <template #footer>
      <el-button @click="handleClose(false)">取消</el-button>
      <el-button type="primary" :loading="loadings.submit" :disabled="!fileList.length" @click="submit"> 保存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from "element-plus"
import { uploadSignUrl } from "@/api/public"

import { downloadTemplate, expenseCustomImport } from "../../api"

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  importUrl: { type: String, default: "" },
  downloadUrl: { type: String, default: "" },
  tableRef: { type: Object, default: () => ({}) },
  task: Boolean,
})

let ossParams = reactive({
  host: "",
})
const extraData = reactive({})
const uploadPercent = ref(0)

let loadings = reactive({})

const emit = defineEmits(["update:modelValue", "refresh"])

const fileList = ref([])
const fileName = ref("")
const remark = ref("")
const upload = ref()

onMounted(() => {
  initUpload()
})

const initUpload = async () => {
  const { data } = await uploadSignUrl({ dir: "import/expense/" })
  console.warn(data)
  ossParams = {
    ...data?.signature,
  }
}

const handleDownload = async () => {
  const { data } = await downloadTemplate()
  console.warn(data)
  if (data.template_url) {
    window.open(data.template_url, "noopener", "noreferrer")
  }
}

const handleExceed = (files) => {
  upload.value?.clearFiles()
  const file = files[0]
  upload.value?.handleStart(file)
}

const get_suffix = (name) => {
  const pos = name.lastIndexOf(".")
  let suffix = ""
  if (pos != -1) {
    suffix = name.substring(pos)
  }
  return suffix
}

const handleChange = async (file) => {
  console.warn(file)
  await initUpload()
  upload.value.submit()
}

const beforeUpload = async (file) => {
  if (file.size > 1024 * 1024 * 1024) {
    ElMessage.warning("上传视频大小不能超过1G")
    return false
  }

  uploadPercent.value = 0
  try {
    await initUpload()
    const { policy, accessid, dir, signature, callback } = ossParams || {}
    console.warn(file)
    const name = `${file.name.split(".")[0]}${+new Date()}`
    const _fileName = name + get_suffix(file.name)
    extraData.key = dir + _fileName
    // extraData.key = '/import/expense/' + _fileName

    extraData.policy = policy
    extraData.OSSAccessKeyId = accessid
    extraData.signature = signature
    fileName.value = _fileName
    return true
  } catch (err) {
    fileName.value = ""
    console.log(err)
    ElMessage.error(err.message)
    return false
  }
}

const handleUploadProgress = (e) => {
  uploadPercent.value = parseInt(e.percent)
}

const handleUploadError = (err) => {
  fileName.value = ""
  ElMessage.error(`上传失败 ${err.toString()}`)
  uploadPercent.value = 0
}

const handleUploadSuccess = (res, file, fileList) => {
  ElMessage.success("上传成功")
}

const handleClose = (refresh) => {
  fileList.value = []
  fileName.value = ""
  remark.value = ""
  emit("update:modelValue", false)
  if (refresh) emit("refresh")
}

const submit = async () => {
  loadings.submit = true
  try {
    if (!fileName.value) {
      ElMessage.warning("请检查文件是否上传")
      return
    }
    await expenseCustomImport({
      file_name: fileName.value,
      file_path: `${ossParams.dir}${fileName.value}`,
      //  file_path: `import/expense/${fileName.value}`,
      remark: remark.value || undefined,
    })
    handleClose(true)
  } catch (e) {
    console.error(e)
  } finally {
    loadings.submit = false
  }
}
</script>

<style lang="scss" scoped>
.v-import {
  :deep(.el-upload-dragger) {
    padding: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-color: #3366f1;
  }
}
</style>
